#!/usr/bin/perl

use Getopt::Std;

getopts( "i:o:", \%opts );

my $file = $opts{i};
my $out = $opts{o};

$out = "-" if ( not defined $opts{o});

if (not defined $opts{i})
{
    print "Usage :\n";
    print "\t$0 -i <XML Final cut pro X file *.fcpxml>\n";
    print "\t$0 -i <XML Final cut pro X file> -o <Output Chapter file>";
    print "\t$0 -i my_movie.fcpxml -o  my_movie.txt";
    print "\n";
    exit 1;
}

open(EXT,"$file") or die "Impossible d'ouvrir le fichier \"$file\" $!";
open(OUT,">$out") or die "Impossible d'ouvrir le fichier \"$out\" $!";

my $clipvalue;
my $clipsec1;
my $clipsec2;
my $chaptervalue;
my $chaptersec1;
my $compt = 0;


    
while(<EXT>){
    s/^\s+//;

    if ( /<clip offset="([0-9]+)\/([0-9]+)s"/ ) 
    {
            $clipvalue = $_;
            $clipsec1 = $1;
            $clipsec2 = $2;
    }
    else 
    {

            if ( /<marker start="([0-9]+)s".*value="(.*)"/ )
            {
                $compt++;
                $chaptersec1 = $1;
                $chaptervalue = $2;
                my $sec;
                if ($clipsec2 == 0) 
                {
                    $sec = 0;
                }
                else
                {
                    $sec = $clipsec1/$clipsec2+$chaptersec1;
                }
                my $time = &sec2time($sec);
                print OUT sprintf "CHAPTER%.2d=$time.000\n", $compt;
                print OUT sprintf "CHAPTER%.2dNAME=$chaptervalue\n", $compt;
            }
    }   
}

close(EXT);
close(OUT);


sub sec2time
{
    my ($sec) = @_ ;
    ($sec)= sprintf "%0.f", $sec;
    my $hours = $sec / 3600 ;
    my $minutes = ($sec%3600) / 60;
    my $secondes = $sec % 60 ;
    
    return sprintf "%.2d:%.2d:%.2d", $hours,$minutes,$secondes;
}

